package com.settlement.system.controller;

import com.settlement.system.common.enums.ReturnStatusEnum;
import com.settlement.system.common.exception.ServiceException;
import com.settlement.system.model.entity.common.TblOrderCloseAccount;
import com.settlement.system.model.entity.common.TblOrderFinAdjustAccount;
import com.settlement.system.model.entity.common.TblReceiveRefundAccount;
import com.settlement.system.model.entity.common.TblReceiveRefundShop;
import com.settlement.system.reply.ObjectDataResponse;
import com.settlement.system.service.*;
import com.settlement.system.common.util.common.FasUtil;
import com.settlement.system.common.util.common.RedisUtil;
import com.alibaba.excel.context.AnalysisContext;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * 订单稽核-财务调账表 前端控制器
 *
 * @author Ximi
 * @since 2020-09-09
 */

@Slf4j
@Api(tags = "订单稽核-财务调账表", description = "订单稽核-财务调账表")
@RestController
@RequestMapping("/order/fin/adjust/account")
public class TblOrderFinAdjustAccountController extends ExcelController<TblOrderFinAdjustAccount> {

    @Resource
    private ITblReceiveRefundShopService tblReceiveRefundShopService;

    @Resource
    private ITblReceiveRefundAccountService tblReceiveRefundAccountService;

    @Resource
    private ITblOrderCloseAccountService orderCloseAccountService;

    @Resource
    private ITblOrderFinAdjustAccountService tblOrderFinAdjustAccountService;

    public static final String FINAD_JUST_BATCH_NUMBER = "acs_order_audit_batch_number";


    @Override
    public IBaseService init() {
        return tblOrderFinAdjustAccountService;
    }

    @Override
    public Class<?> getModelClass() {
        return TblOrderFinAdjustAccount.class;
    }

    @Override
    protected void setParamsModel(Map<String, Object> model) {
        FasUtil.formatInQueryCondition(model, "spOrderNo", "shopNo","channelNos","batchNumber");
        super.setParamsModel(model);
    }

    @Override
    public String verifyImportObject(TblOrderFinAdjustAccount tblOrderFinAdjustAccount, AnalysisContext analysisContext) {

        if(tblOrderFinAdjustAccount.getOutDate() == null){
            return "发生日期不能为空";
        }

        if(tblOrderFinAdjustAccount.getAdjustAmount() == null){
            return "金额不能为空";
        }

        if (StringUtils.isEmpty(tblOrderFinAdjustAccount.getShopNo())
                && StringUtils.isEmpty(tblOrderFinAdjustAccount.getShopAccount())) {
            return "店铺编码、店铺账号不能同时空";
        }

        try {

            TblOrderCloseAccount closeAccount = null;
            if (!StringUtils.isEmpty(tblOrderFinAdjustAccount.getShopNo())) {
                TblReceiveRefundShop receiveRefundShop = tblReceiveRefundShopService.getByShopNo(tblOrderFinAdjustAccount.getShopNo());
                if (receiveRefundShop == null) {
                    return "店铺在店铺设置中不存在";
                }
                tblOrderFinAdjustAccount.setEnterAccountBody(receiveRefundShop.getNcEnterAccountBody());
                tblOrderFinAdjustAccount.setChannelNo(receiveRefundShop.getChannelNo());
                tblOrderFinAdjustAccount.setChannelName(receiveRefundShop.getChannelName());
                tblOrderFinAdjustAccount.setShopName(receiveRefundShop.getShopName());
                closeAccount = orderCloseAccountService.getByThreeChannelNoAndShopAccount(receiveRefundShop.getThreeChannelNo(), null);
            }

            if (!StringUtils.isEmpty(tblOrderFinAdjustAccount.getShopAccount()) && StringUtils.isEmpty(tblOrderFinAdjustAccount.getShopNo())) {
                TblReceiveRefundAccount refundAccount = tblReceiveRefundAccountService.getOrByShopAccount(tblOrderFinAdjustAccount.getShopAccount());
                if (null == refundAccount) {
                    return "店铺账号在账号设置中不存在";
                }
                tblOrderFinAdjustAccount.setEnterAccountBody(refundAccount.getNcEnterAccountBody());
                tblOrderFinAdjustAccount.setChannelNo(refundAccount.getChannelNo());
                tblOrderFinAdjustAccount.setChannelName(refundAccount.getChannelName());
                closeAccount = orderCloseAccountService.getByThreeChannelNoAndShopAccount(null, refundAccount.getShopAccount());
            }

            if (closeAccount == null) {
                return "请先设置关账";
            }

            if (tblOrderFinAdjustAccount.getOutDate().compareTo(closeAccount.getRealCloseAccountDate()) <= 0) {
                return "发生日期必须大于关账日";
            }

            tblOrderFinAdjustAccount.setFlag(0);

        } catch (Exception ex) {
            log.error("验证稽核调账异常", ex);
            return "系统异常";
        }
        return null;
    }


    @Override
    protected void saveData(List<TblOrderFinAdjustAccount> datas) throws ServiceException {
        if(!CollectionUtils.isEmpty(datas)){
            long batchNumber = RedisUtil.incr(FINAD_JUST_BATCH_NUMBER, 1);
            datas.forEach(tblOrderFinAdjustAccount -> {
                tblOrderFinAdjustAccount.setBatchNumber(batchNumber);
            });
            this.message.set("数据导入成功，批次号为"+String.valueOf(batchNumber));
        }
        super.saveData(datas);
    }

    @Override
    @CacheEvict(cacheNames = {"closeAccountByThreeChannelNoAndShopAccount","rrShopByShopNo","closeAccountByThreeChannelNoAndShopAccount"},
            allEntries = true,beforeInvocation = true)
    public ObjectDataResponse batchDelete(@RequestBody List<TblOrderFinAdjustAccount> deleteList, HttpServletRequest request) {

        try {
            for (int index = 0; index < deleteList.size(); index++) {
                TblOrderCloseAccount closeAccount = null;
                TblOrderFinAdjustAccount adjustAccount = tblOrderFinAdjustAccountService.getById(deleteList.get(index).getId());
                if (adjustAccount != null) {
                    if (!StringUtils.isEmpty(adjustAccount.getShopNo())) {
                        TblReceiveRefundShop refundShop = tblReceiveRefundShopService.getByShopNo(adjustAccount.getShopNo());
                        if (refundShop != null && !StringUtils.isEmpty(refundShop.getThreeChannelNo())) {
                            closeAccount = orderCloseAccountService.getByThreeChannelNoAndShopAccount(refundShop.getThreeChannelNo(), null);
                        }
                    } else {
                        closeAccount = orderCloseAccountService.getByThreeChannelNoAndShopAccount(null, adjustAccount.getShopAccount());
                    }
                }

                if (closeAccount != null && adjustAccount != null && closeAccount.getRealCloseAccountDate().compareTo(adjustAccount.getOutDate()) >= 0) {
                    return new ObjectDataResponse(ReturnStatusEnum.CHECK_FAILURE.getValue(), "第" + (index + 1) + "行已经关账");
                }
            }
            tblOrderFinAdjustAccountService.virtualDelete(deleteList);
        } catch (Exception ex) {
            return new ObjectDataResponse(ReturnStatusEnum.REQUEST_ABNORMAL);
        }
        return new ObjectDataResponse(ReturnStatusEnum.REQUEST_SUCCESS);
    }

    @Override
    @PostMapping("import")
    @CacheEvict(cacheNames = {"closeAccountByThreeChannelNoAndShopAccount","rrOrAccountByLoginAccount","rrShopByShopNo"},
            allEntries = true,beforeInvocation = true)
    public ObjectDataResponse importFile(MultipartFile file, HttpServletRequest request) {
        return super.importFile(file, request);
    }

    @Override
    protected void setFootModel(Map<String, Object> result, Map<String, Object> model) throws ServiceException {
        try {
            result.put("foot",tblOrderFinAdjustAccountService.selectFoot(model));
        } catch (ServiceException e) {
            throw new ServiceException(e);
        }
    }
}

